#!/bin/bash
set -e

cmd_query(){
  local action="$1"
  local json="$2"
  curl -s -H "Content-Type:application/json" \
	-H "Authorization: token $token" \
	-d "$json" "$base_url/open-api?Action=$action"
}

cmd_teams(){
  cmd_query DescribeUserProjects '{"Action": "DescribeUserProjects", "userId": '"$userId}"
}

cmd_getProjectId(){
  local team_name="$1"
  cmd_teams | jq -r ".Response.ProjectList[] | select( .Name == \"$team_name\" ) | .Id"
}

cmd_createProject(){
  local project_name="$1"
  local description="$2"
  cmd_query CreateCodingProject '{
    "Action": "CreateCodingProject",
	"Name": "'"$project_name"'",
	"DisplayName": "'"$project_name"'",
	"Description": "'"$description"'",
	"GitReadmeEnabled": false,
	"VcsType": "git",
	"CreateSvnLayout": false,
	"Shared": 1,
	"ProjectTemplate": "CODE_HOST"
  }' | jq -r '.Response.ProjectId'
}

cmd_createRepo(){
  local project_id="$1"
  local repo_name="$2"
  cmd_query CreateGitDepot '{
	"Action": "CreateGitDepot",
	"ProjectId": '"$project_id"',
	"DepotName": "'"$repo_name"'"
  }' | jq -r '.Response.DepotId'
}

cmd_lsRepo(){
  local project_id="$1"
  cmd_query DescribeProjectDepotInfoList '{
	"Action": "DescribeProjectDepotInfoList",
	"ProjectId": '"$project_id"'
  }' | jq -r '.Response.DepotData.Depots[].Name'
}

cmd_rmRepo(){
  local project_id="$1"
  local repo_name="$2"
  local repo_id="$(
	cmd_query DescribeProjectDepotInfoList '{
	  "Action": "DescribeProjectDepotInfoList",
	  "ProjectId": '"$project_id"'
	}' | jq -r '.Response.DepotData.Depots[] | select( .Name == "'"$repo_name"'" ) | .Id'
  )"
  [ "$repo_id" ] || return 1
  cmd_query DeleteGitDepot '{
    "Action": "DeleteGitDepot",
    "DepotId": '"$repo_id"'
  }'
}

load_configure(){
  # 读取设置
  local conf="$HOME/.config/fkcloud/backends/codingctl.env"
  source "$conf"
  local configs=(
	base_url
	token
	team
  )
  local config
  for config in ${configs[@]}; do
	eval "value=\"\$$config\""
	if [ ! "$value" ]; then
	  echo "$config is not set in $conf" >&2
	  return 1
	fi
  done

  # 验证 api
  local me="$(curl -s -H "Authorization: token $token" "$base_url/api/me")"
  test "$(echo "$me" | jq -r '.team')" == "$team"

  # 用户 id
  userId="$(echo "$me" | jq -r '.id')"
}

cmd_ls(){
  :
}

cmd_pull(){
  :
}

cmd_push(){
  :
}

cmd_rm(){
  :
}

cmd_help(){
  printf 'Usage: %s COMMAND

Commands:
  ls
  pull
  push
  rm
' "$0"
}

main(){
  local cmd="$1"
  shift || true
  [ "$cmd" ] || cmd=help
  if ! type "cmd_$cmd" >/dev/null 2>&1; then
	cmd_help
	return 1
  fi
  load_configure
  cmd_$cmd "$@"
}

main "$@"

